/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.classes;

import java.util.ArrayList;
import java.util.List;

/**
 * This class is a wrapper class that collects the list of courses and then
 * calculates the gpa based on their grades.
 * @author 
 *
 */
public class Calculator {
	private ArrayList<Course> courses;
	private ArrayList<UofTGrade> grades;
	private double _gpa;
	private double _totalWeights=0;
	private double _sumGpa=0;
	
	public Calculator(List<Course> courses) {
		this.courses = new ArrayList<Course>(courses);
		this.grades = new ArrayList<UofTGrade>();
		this.updateGrades();
	}
	
	/**
	 * Recalculates all the necessary fields.
	 */
	public void updateGrades() {
		
		for (Course course : this.courses) {
			grades.add(course.get_grade());
			_totalWeights+=course.get_weight();
			_sumGpa+=course.get_grade().get_GPA()*course.get_weight();
		}
	}
	
	/**
	 * Calculates the gpa.
	 * @return the gpa
	 */
	public double get_GPA() {
		double GPA, sumGPA=0, courseGPA, courseWeight, totalWeight=0;
		
		for (UofTGrade grade : this.grades) {
			courseGPA = grade.get_GPA();
			courseWeight = grade.get_weight();
			totalWeight += courseWeight;
			sumGPA += courseGPA * courseWeight;
		}
		
		if (totalWeight > 0)
			GPA = sumGPA / totalWeight;
		else
			GPA = 0;
		
		return GPA;
	}
	
	public double get_sumGpa() {
		return _sumGpa;
	}
	
	public double get_totalWeights() {
		return _totalWeights;
	}
	
	/**
	 * Updates the course list and recalculates all the necessary fields.
	 */
	public void setCourses(ArrayList<Course> courses) {
		this.courses = courses;
		updateGrades();
	}
}
